package com.zking.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.awt.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * webflux 案例测试
 * 张志鹏 2020-10-03
 */
@RestController
public class TestController {
    Logger logger=LoggerFactory.getLogger(TestController.class);
    /**
     * 这是传统的方式
     * @return
     */
    @GetMapping("/test")
    public String test(){
        logger.info("test1 start");
       String result=createStr();
        logger.info("test1 end");
       return result;
    }
    /**
     * 这是webflux 方式
     * @return
     */
    @GetMapping("/test2")
    private Mono<String> get2(){
        logger.info("test1 start");
        Mono<String> result=Mono.fromSupplier(()->createStr());
        logger.info("test1 end");
        return result;
    }
    @GetMapping(value = "/test3",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    private Flux<String> get3(){
        logger.info("test1 start");
      Flux<String> result = Flux.fromStream(IntStream.range(1, 5).mapToObj(i -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "flux data --" + i;
        }));
        logger.info("test1 end");
        return result;
    }
    //为了检验 同步和异步的区别 传统模式花了5秒钟时间 异步方式基本没耗时间
    private String createStr(){
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return "hello world";
    }

}
